using System.Data;
using Admin2025.Application.Dtos;
using Admin2025.Application.IServices;
using Admin2025.Domain.Entities.App;
using Dapper;
using Microsoft.AspNetCore.Mvc;
// using BCrypt.Net;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{

  private readonly IAuthService _authService;
  private readonly IDbConnection _db;
  private static int _seeded = 0;

  public AuthController(IAuthService authService, IDbConnection db)
  {
    _authService = authService;
    _db = db;

    // 仅第一次实例化时执行
    if (Interlocked.CompareExchange(ref _seeded, 1, 0) == 0)
    {
      SeedSuperAdminAsync(db).GetAwaiter().GetResult();
    }
  }

  [HttpPost("login")]
  public async Task<IActionResult> Login([FromBody] LoginDto dto)
  {
    var result = await _authService.LoginAsync(dto);
    if (result == null)
    {
      return Unauthorized("Invalid credentials");
    }
    return Ok(new { Token = result.Value.Token, User = result.Value.User });
    // return success ? Ok("Login successful") : Unauthorized("Invalid credentials");
  }

  [HttpPost("register")]
  public async Task<IActionResult> Register([FromBody] RegisterDto dto)
  {
    var result = await _authService.RegisterAsync(dto);
    if (result == null)
    {
      return BadRequest("Username already exists");
    }
    return Ok(new { Token = result.Value.Token, User = result.Value.User });
    // return success ? Ok("Registration successful") : BadRequest("Username already exists");
  }

  private async Task SeedSuperAdminAsync(IDbConnection db)
  {
    // 1. 确保 SuperAdmin 角色
    var superRoleId = await _db.QueryFirstOrDefaultAsync<Guid?>(
        "SELECT Id FROM AppRoles WHERE RoleName = @RoleName",
        new { RoleName = AppRole.SuperAdminRoleName });

    System.Console.WriteLine("超级管理员" + superRoleId);

    if (!superRoleId.HasValue)
    {
      superRoleId = Guid.NewGuid();
      await db.ExecuteAsync(
          @"INSERT INTO AppRoles(Id, RoleName, Description, DataScope)
                  VALUES(@Id, @RoleName, @Desc, 'All')",
          new
          {
            Id = superRoleId,
            RoleName = AppRole.SuperAdminRoleName,
            Desc = "System Super Administrator"
          });
      System.Console.WriteLine(1111);
    }

    // 2. 确保 SuperAdmin 用户
    var superUserId = await _db.QueryFirstOrDefaultAsync<Guid?>(
        "SELECT Id FROM AppUsers WHERE UserName = @UserName",
        new { UserName = "SuperAdmin" });

    if (!superUserId.HasValue)
    {
      superUserId = Guid.NewGuid();
      var salt = BCrypt.Net.BCrypt.GenerateSalt(); // 自动生成盐值
      var pwdHash = BCrypt.Net.BCrypt.HashPassword("Admin2025!", salt);

      await _db.ExecuteAsync(
          @"INSERT INTO AppUsers(Id, UserName, Email, PasswordHash, Salt)
              VALUES(@Id, @UserName, @Email, @Pwd, @Salt)",
          new
          {
            Id = superUserId,
            UserName = "SuperAdmin",
            Email = "SuperAdmin@admin2025.com",
            Pwd = pwdHash,
            Salt = salt
          });
      Console.WriteLine("SuperAdmin user created.");
    }

    // 3. 绑定用户与角色（幂等）
    var exists = await _db.QueryFirstOrDefaultAsync<int?>(
        "SELECT 1 FROM UserRoles WHERE UserId = @UserId AND RoleId = @RoleId",
        new { UserId = superUserId, RoleId = superRoleId });

    if (exists == null)
    {
      await _db.ExecuteAsync(
          "INSERT INTO UserRoles(UserId, RoleId) VALUES(@UserId, @RoleId)",
          new { UserId = superUserId, RoleId = superRoleId });
    }
  }

}